import { addTree, getTree, putTree, delTree } from '@/api/test/index';
import { postTree } from '@/pages/CodeTables/specification';
import { message } from 'ant-design-vue';
const postData = {
  directoryCode: '',
  directoryName: '',
  menuCode: '40081',
  parentCode: '',
  status: '',
};
// 向后端传递数据
let data: postTree = reactive(postData);
// 页面展示数
const dataTree = ref<[]>([]);
// 等待
const loading = ref<boolean>(false);
// 将树结构扁平化
const flattenList: { directoryCode: string; directoryName: string }[] = [];
// 递归遍历树结构并扁平化push到flattenList里面
const generateList = (dataTree: []) => {
  for (let i = 0; i < dataTree.length; i++) {
    const { directoryCode, directoryName, children = [] } = dataTree[i];
    flattenList.push({ directoryCode, directoryName });
    if (children.length) {
      generateList(children as []);
    }
  }
};
// 查询树节点
const getTreeStructure = async () => {
  loading.value = true;
  try {
    const res = await getTree(data.menuCode);
    dataTree.value = res as [];
    generateList(dataTree.value);
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};
// 增加树节点
const addTreeStructure = async () => {
  try {
    await addTree(data);
    data = reactive(postData);
    message.success('新增成功');
    console.log(data);
  } catch (error) {
    message.error('新增失败');
  }
};
// 修改树节点
const updataTreeStructure = async () => {
  try {
    await putTree(data);
    console.log(data);
  } catch (error) {
    message.error('修改失败');
  }
};
// 删除树节点
const delTreeStructure = async () => {
  try {
    const res = await delTree(data.directoryCode);
    dataTree.value = res as [];
    message.success('删除成功');
  } catch (error) {
    message.success('删除失败');
  }
};
export function TreeHooks() {
  return {
    getTreeStructure,
    addTreeStructure,
    updataTreeStructure,
    delTreeStructure,
    data,
    dataTree,
    loading,
    flattenList,
  };
}
